const axios = require('axios')
import qs from 'qs'
import store from '../store'
import { Toast } from 'vant';
axios.default.timeout = 5000
const BASE_URL = process.env.NODE_ENV === 'production' ? 'http://testwo.longde999.cn/web' : '/api';
axios.default.baseUrl = BASE_URL;

//axios.defaults.withCredentials = true
console.log("axios", axios)
//请求拦截
axios.interceptors.request.use(
    config => {
        if (store.state.token) {
            config.data = config.data + '&user_token=' + store.state.token;
        }
        // if (process.env.NODE_ENV === 'production') {
        //     config.data = config.data + `&school_dns=${window.location.host}&dns=${window.location.host}`;
        // } else {
        //     config.data = config.data + '&school_dns=testwo.admin.longde999.cn&dns=testwo.admin.longde999.cn';
        // }
        config.data = config.data + '&school_dns=testwo.admin.longde999.cn&dns=testwo.admin.longde999.cn';
        return config;
    },
    error => {
        return Promise.error(error);
    }
)

//响应拦截
axios.interceptors.response.use(
    response => {
        if (response.data.code == 401) {
            Toast(response.data.msg);
            store.commit("clearToken");
            // Message({
            //     showClose: true,
            //     message: response.data.msg,
            //     type: 'error'
            // });
            // setTimeout(() => {
            //     history.pushState(null, null, "/login")
            // }, 1000)
        }
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {
            return Promise.resolve(response);
        }
    },
    error => {
        if (error) {
            return Promise.reject(error);
        } else {
            console.log(error);
        }
    }
);
// 自定义判断元素类型JS
function toType(obj) {
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull(o) {
    for (var key in o) {
        if (o[key] === null) {
            delete o[key]
        }
        if (toType(o[key]) === 'string') {
            o[key] = o[key].trim()
        } else if (toType(o[key]) === 'object') {
            o[key] = filterNull(o[key])
        } else if (toType(o[key]) === 'array') {
            o[key] = filterNull(o[key])
        }
    }
    return o
}
function apiAxios(method, url, params) {
    return new Promise((resolve, reject) => {
        // if (params) {
        //   params = filterNull(params);
        // }
        axios({
            method: method,
            url: url,
            data: method === 'POST' || method === 'PUT' ? params : null,
            params: method === 'GET' || method === 'DELETE' ? params : null,
            baseURL: axios.default.baseUrl,
            withCredentials: true
        }).then(res => {
            console.log(params)
            if (params && params.msg) {
                let varctorl = ''
                for (var key in msgType) {
                    if (key == params.msgcode) {
                        varctorl = msgType[key][params.msg.cmdtype]
                    }
                }
                if (res.data.code == 1) {
                    // Message({
                    //     message: varctorl + '命令已发送！等待设备响应',
                    //     type: 'success',
                    //     duration: 3000,
                    //     offset: 150
                    // })
                }
            }
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

// 返回在vue模板中的调用接口
export default {
    get: function (url, params) {
        return apiAxios('GET', url, params)
    },
    post: function (url, params) {
        return apiAxios('POST', url, qs.stringify(params))
    },
    put: function (url, params) {
        return apiAxios('PUT', url, params)
    },
    delete: function (url, params) {
        return apiAxios('DELETE', url, params)
    }
}
